import tkinter as tk
from tkinter import messagebox
import sqlite3
import hashlib
import os

DATABASE = 'users.db'

def create_user_table():
    with sqlite3.connect(DATABASE) as conn:
        cursor = conn.cursor()
        cursor.execute('''CREATE TABLE IF NOT EXISTS users (
                            id INTEGER PRIMARY KEY AUTOINCREMENT,
                            username TEXT UNIQUE NOT NULL,
                            password TEXT NOT NULL)''')
        cursor.execute('''CREATE TABLE IF NOT EXISTS history (
                            id INTEGER PRIMARY KEY AUTOINCREMENT,
                            user_id INTEGER,
                            constructionTime TEXT,
                            square TEXT,
                            livingRoom TEXT,
                            drawingRoom TEXT,
                            kitchen TEXT,
                            bathRoom TEXT,
                            floor TEXT,
                            subway TEXT,
                            prediction TEXT,
                            FOREIGN KEY (user_id) REFERENCES users (id))''')
        conn.commit()

def hash_password(password):
    return hashlib.sha256(password.encode()).hexdigest()

#创建一个默认账号
def insert_default_user():
    username = "root"
    password = "12345"
    hashed_password = hash_password(password)

    with sqlite3.connect(DATABASE) as conn:
        cursor = conn.cursor()
        try:
            cursor.execute("INSERT INTO users (username, password) VALUES (?, ?)", (username, hashed_password))
            conn.commit()
        except sqlite3.IntegrityError:
            # User already exists
            pass

class LoginRegisterApp(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("用户登录/注册")
        self.geometry("300x200")
        create_user_table()
        self.create_widgets()

    def create_widgets(self):
        self.label_username = tk.Label(self, text="用户名")
        self.label_username.pack()
        self.entry_username = tk.Entry(self)
        self.entry_username.pack()

        self.label_password = tk.Label(self, text="密码")
        self.label_password.pack()
        self.entry_password = tk.Entry(self, show='*')
        self.entry_password.pack()

        self.login_button = tk.Button(self, text="登录", command=self.login)
        self.login_button.pack()

        self.register_button = tk.Button(self, text="注册", command=self.register)
        self.register_button.pack()

    def login(self):
        username = self.entry_username.get()
        password = self.entry_password.get()

        if not username or not password:
            messagebox.showwarning("输入错误", "用户名和密码不能为空")
            return

        hashed_password = hash_password(password)

        with sqlite3.connect(DATABASE) as conn:
            cursor = conn.cursor()
            cursor.execute("SELECT * FROM users WHERE username=? AND password=?", (username, hashed_password))
            user = cursor.fetchone()
            if user:
                self.destroy()
                os.system(f'python gui.py {user[0]}')
            else:
                messagebox.showerror("错误", "用户名或密码错误")

    def register(self):
        username = self.entry_username.get()
        password = self.entry_password.get()

        if not username or not password:
            messagebox.showwarning("输入错误", "用户名和密码不能为空")
            return

        hashed_password = hash_password(password)

        with sqlite3.connect(DATABASE) as conn:
            cursor = conn.cursor()
            try:
                cursor.execute("INSERT INTO users (username, password) VALUES (?, ?)", (username, hashed_password))
                conn.commit()
                messagebox.showinfo("成功", "注册成功，请登录")
            except sqlite3.IntegrityError:
                messagebox.showerror("错误", "用户名已存在")

if __name__ == "__main__":
    app = LoginRegisterApp()
    app.mainloop()